<?php
declare(strict_types=1);

namespace So;

use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Response as HyperfResponse;
use Psr\Http\Message\ResponseInterface;

/**
 * 新增Respone方法
 * @author Saopig <1306222220@qq.com>
 */
class Response extends HyperfResponse
{
    /**
     * @param string|int $msg
     * @param mixed|array $data
     * @param string $url
     * @param int $code
     * @return ResponseInterface
     */
    public function success(string|int $msg = '', mixed $data = [], string $url = '', int $code = 1): ResponseInterface
    {
        if (is_int($msg) && $data) {
            $data = ['total' => $msg, 'rows' => $data];
            $msg = '';
        }
        $array = [
            'code' => $code,
            'msg' => $msg,
        ];
        $data && $array['data'] = $data;
        $url && $array['url'] = $url;
        return $this->getResponse()->withBody(new SwooleStream($this->toJson($array)))->withHeader('content-type', 'application/json; charset=utf-8');
    }

    /**
     * @param string $msg
     * @param int $code
     * @param mixed|array $data
     * @param string $url
     * @return ResponseInterface
     */
    public function error(string $msg = '', int $code = 0, mixed $data = [], string $url = ''): ResponseInterface
    {
        $array = [
            'code' => $code,
            'msg' => $msg,
        ];
        $data && $array['data'] = $data;
        $url && $array['url'] = $url;
        return $this->getResponse()->withBody(new SwooleStream($this->toJson($array)))->withHeader('content-type', 'application/json; charset=utf-8');
    }
}